import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ret = new ArrayList<>();
        int n = matrix.length;
        int m = matrix[0].length;
        int up = 0, down = n - 1, left = 0, right = m - 1;
        while(true){
            //上
            for(int i = left; i <= right; i++){
                ret.add(matrix[up][i]);
            }
            if(++up > down) break;
            //右
            for(int i = up; i <= down; i++){
                ret.add(matrix[i][right]);
            }
            if(--right < left) break;
            //下
            for(int i = right; i >= left; i--){
                ret.add(matrix[down][i]);
            }
            if(--down < up) break;
            //左
            for(int i = down; i >= up; i--){
                ret.add(matrix[i][left]);
            }
            if(++left > right) break;
        }
        return ret;
    }
}